def kmeans(array,count)
  init = [] # 初始点数组
  dSum = [] # 分类求和数组
  cCount = [] # 分类个数数组
  dArray=[] # 距离数组
  cArrayOld=[] # 上次的选择数组
  cArray=[] # 选择哪个原点的数组
  cIndexArray = [] #选择的那个点的索引的数组
  count.times {init.push(array[rand(array.length)])}
  array.length.times {cArrayOld.push(0)}

  while(true)
    dSum = []
    cCount = []
    dArray=[]
    cArray=[]
    cIndexArray = []
    count.times {dSum.push(0)}
    count.times {cCount.push(0)}
    array.length.times {dArray.push(999)}
    array.length.times {cArray.push(0)}
    array.length.times {cIndexArray.push(0)}

    for i in 0...array.length
      for j in 0...init.length
        d = distance(array[i],init[j])
          if d < dArray[i]
            dArray[i] = d 
            cArray[i] = init[j]
            cIndexArray[i] = j
          end
      end
    end
    p cArray
    p init
   
    if cArray.eql?(cArrayOld)
       break
    end
    # 重新计算点
    for i in 0...array.length
      cArrayOld[i] = cArray[i]
      index = cIndexArray[i]
      cCount[index] = cCount[index] + 1
      dSum[index] = dSum[index] + array[i]
    end

    for i in 0...count
      if cCount[i] > 0
        init[i] = dSum[i] / cCount[i]
      end
    end
    p init
    puts "----------------------"
  end
end

def distance(a,b)
    return (b-a).abs()
end
array = [1,2,3,6,7,9]
kmeans(array,2)